<template>
  <section class="app-inner">
    <el-dialog
      :title="addStudentForm.title"
      :visible.sync="addStudentForm.flag"
      width="70%"
      modal
      center
      top="5vh"
      show-close
      @open="openFormDialog"
    >
      <el-dialog
        width="30%"
        title="提示"
        :visible.sync="innerVisible"
        append-to-body
        center
      >
        <div :style="{ paddingBottom: '25px' }">
          系统已存在 “{{ oldAccount }}” 账号，自动修改您的账号为 “{{
            innerDialogText
          }}”，是否继续保存？
        </div>
        <div
          class="foot"
          :style="{ display: 'flex', justifyContent: 'center' }"
        >
          <el-button type="primary" @click.native.prevent="closeInnerDialog"
            >否</el-button
          >
          <el-button type="primary" @click.native.prevent="resetName">
            是
          </el-button>
        </div>
      </el-dialog>

      <el-dialog
        width="40%"
        title="批量上传学生荣誉"
        :visible.sync="isImportHonor"
        append-to-body
        center
      >
        <div :style="{ paddingBottom: '25px' }">
          <el-upload
            style="margin-bottom: 30px"
            :show-file-list="false"
            action="/gateway/api/basic/studentHonor/batchImport"
            :headers="headerObj"
            :on-success="handlefileSuccess"
            :before-upload="beforeUpload"
            :data="{ studentCode: infoForm.code }"
          >
            <el-button type="primary">上传文件</el-button>
          </el-upload>
          <div class="import-honor-des">
            <div class="title">导入说明</div>
            <div class="box1">
              <span
                >1.
                导入的文件格式为Excel或压缩包格式，后缀名为.xls或.xlsx或zip；</span
              >
              <el-button type="text" class="btn" @click="honorTemplate"
                >点击下载模板文件</el-button
              >
            </div>
            <p class="text">2. 导入的文件应该放在文件的第一个工作表中；</p>
            <p class="text">3. 请勿修改您下载模板的标题（前三行）；</p>
            <p class="text">4. 请务必填写表格中必填信息；</p>
          </div>
        </div>
        <div
          class="foot"
          :style="{ display: 'flex', justifyContent: 'center' }"
        >
          <el-button type="primary" @click.native.prevent="closeImportHonor"
            >取消</el-button
          >
        </div>
      </el-dialog>
      <div style="position: relative">
        <el-tabs v-model="activeName">
          <el-tab-pane label="基本信息" name="1" class="info-school-tab">
            <el-form
              ref="basicForm"
              :model="infoForm"
              label-width="140px"
              :rules="rules"
              size="small"
            >
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="学生姓名" prop="name">
                    <el-input
                      v-model="infoForm.name"
                      placeholder="请输入"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="学籍号" prop="code">
                    <el-input
                      v-model="infoForm.code"
                      placeholder="请输入"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="姓名拼音" prop="pinyinName">
                    <el-input
                      v-model="infoForm.pinyinName"
                      placeholder="请输入"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="英文姓名" prop="englishName">
                    <el-input
                      v-model="infoForm.englishName"
                      placeholder="请输入"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="联系方式" prop="contact">
                    <Acc-desensitization ref="cellularPhone" rule-type='cellularPhone' v-model="infoForm.contact"></Acc-desensitization>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="家庭住址" prop="address">
                    <el-input
                      v-model="infoForm.address"
                      placeholder="请输入"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="是否默认生成账号" prop="isCreateAccount">
                    <el-select
                      placeholder="请选择"
                      filterable
                      v-model="infoForm.isCreateAccount"
                      :disabled="
                        addStudentForm.title === '编辑学生信息' ? true : false
                      "
                    >
                      <el-option label="是" :value="1"></el-option>
                      <el-option label="否" :value="0"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item
                    label="账号"
                    prop="account"
                  >
                    <!-- :rules="
                      infoForm.isCreateAccount === 1
                        ? [
                            {
                              required: true,
                              message: '请输入内容',
                              trigger: ['blur', 'change'],
                            },
                          ]
                        : []
                    " -->
                    <el-input
                      placeholder="请输入"
                      v-model="infoForm.account"
                      :disabled="isDisableAccount"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="所属校区" prop="schoolDistrictNo">
                    <el-select
                      v-model="infoForm.schoolDistrictNo"
                      placeholder="请选择"
                      clearable
                      filterable
                    >
                      <el-option
                        v-for="item in districtData"
                        :key="item.no"
                        :label="item.name"
                        :value="item.no"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="性别" prop="gender">
                    <el-select
                      :disabled="infoForm.cardType === '1'"
                      v-model="infoForm.gender"
                      placeholder="请选择"
                      clearable
                      filterable
                    >
                      <el-option
                        v-for="item in comData['性别']"
                        :key="item.code"
                        :label="item.name"
                        :value="Number(item.code)"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="国籍" prop="nationality">
                    <el-select
                      v-model="infoForm.nationality"
                      placeholder="请选择"
                      clearable
                      filterable
                    >
                      <el-option
                        v-for="item in comData['国籍']"
                        :key="item.code"
                        :label="item.name"
                        :value="item.code"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="证件类型" prop="cardType">
                    <el-select
                      @change="handleChangeCardType"
                      v-model="infoForm.cardType"
                      placeholder="请选择"
                      clearable
                      filterable
                    >
                      <el-option
                        v-for="item in comData['证件']"
                        :key="item.code"
                        :label="item.name"
                        :value="item.code"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="证件号码" prop="idCard">
                    <Acc-desensitization
                      ref="AccDesensitization"
                      :isdesensitization="infoForm.cardType === '1'"
                      @blur="blurSearchIdInfo"
                      v-model="infoForm.idCard"
                    ></Acc-desensitization>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="出生日期" prop="birthday">
                    <el-date-picker
                      :disabled="infoForm.cardType === '1'"
                      format="yyyy-MM-dd"
                      value-format="yyyy-MM-dd"
                      v-model="infoForm.birthday"
                      type="date"
                      style="width: 100%"
                      placeholder="出生日期"
                      :picker-options="setDisabled"
                    >
                    </el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="出生地" prop="birthPlace">
                    <el-cascader
                      :disabled="infoForm.cardType === '1'"
                      style="width: 100%"
                      separator=""
                      filterable
                      :options="regionOptions"
                      v-model="infoForm.birthPlace"
                    >
                    </el-cascader>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="籍贯" prop="nativePlace">
                    <el-cascader
                      :disabled="infoForm.cardType === '1'"
                      style="width: 100%"
                      separator=""
                      filterable
                      :options="regionOptions"
                      v-model="infoForm.nativePlace"
                      ref="nativePlace"
                    >
                    </el-cascader>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="民族" prop="nation">
                    <el-select
                      placeholder="请选择民族"
                      v-model="infoForm.nation"
                      clearable
                      filterable
                    >
                      <el-option
                        v-for="item in comData['民族']"
                        :key="item.code"
                        :label="item.name"
                        :value="String(item.code)"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="政治面貌" prop="politicsStatus">
                    <el-select
                      placeholder="请选择政治面貌"
                      v-model="infoForm.politicsStatus"
                      clearable
                      filterable
                    >
                      <el-option
                        v-for="item in comData['政治']"
                        :key="item.code"
                        :label="item.name"
                        :value="String(item.code)"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="港澳台侨" prop="compatriotCode">
                    <el-select
                      placeholder="请选择港澳台侨"
                      v-model="infoForm.compatriotCode"
                      clearable
                      filterable
                    >
                      <el-option
                        v-for="item in comData['港澳台']"
                        :key="item.code"
                        :label="item.name"
                        :value="String(item.code)"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="宗教信仰" prop="religionCode">
                    <el-select
                      placeholder="请选择宗教信仰"
                      v-model="infoForm.religionCode"
                      clearable
                      filterable
                    >
                      <el-option
                        v-for="item in comData['宗教']"
                        :key="item.code"
                        :label="item.name"
                        :value="String(item.code)"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="健康状况" prop="healthCode">
                    <el-select
                      placeholder="请选择健康状况"
                      v-model="infoForm.healthCode"
                      clearable
                      filterable
                    >
                      <el-option
                        v-for="item in comData['健康']"
                        :key="item.code"
                        :label="item.name"
                        :value="String(item.code)"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="血型" prop="bloodTypeCode">
                    <el-select
                      placeholder="请选择血型"
                      v-model="infoForm.bloodTypeCode"
                      clearable
                      filterable
                    >
                      <el-option
                        v-for="item in comData['血型']"
                        :key="item.code"
                        :label="item.name"
                        :value="String(item.code)"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label="是否独生子女" prop="isOnlyChild">
                    <el-select
                      v-model="infoForm.isOnlyChild"
                      placeholder="请选择"
                    >
                      <el-option label="是" :value="Number(0)"> </el-option>
                      <el-option label="否" :value="Number(1)"> </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item
                    label="是否外来务工人员子女"
                    prop="isMigrantChild"
                  >
                    <el-select
                      v-model="infoForm.isMigrantChild"
                      placeholder="请选择"
                    >
                      <el-option label="是" :value="Number(0)"> </el-option>
                      <el-option label="否" :value="Number(1)"> </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="是否孤儿" prop="isOrphan">
                    <el-select v-model="infoForm.isOrphan" placeholder="请选择">
                      <el-option label="是" :value="Number(0)"> </el-option>
                      <el-option label="否" :value="Number(1)"> </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="是否烈士或优抚子女" prop="isMartyrChild">
                    <el-select
                      v-model="infoForm.isMartyrChild"
                      placeholder="请选择"
                    >
                      <el-option label="是" :value="Number(0)"> </el-option>
                      <el-option label="否" :value="Number(1)"> </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="是否残疾" prop="isDisabled">
                    <el-select
                      v-model="infoForm.isDisabled"
                      placeholder="请选择"
                      @change="isDisabledChange"
                    >
                      <el-option label="是" :value="Number(0)"> </el-option>
                      <el-option label="否" :value="Number(1)"> </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="残疾类型" prop="disabledCode">
                    <el-select
                      :disabled="infoForm.isDisabled === 0 ? false : true"
                      placeholder="请选择残疾类型"
                      v-model="infoForm.disabledCode"
                      clearable
                      filterable
                    >
                      <el-option
                        v-for="item in comData['残疾类型']"
                        :key="item.code"
                        :label="item.name"
                        :value="Number(item.code)"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="是否寄宿" prop="isBoard">
                    <el-select v-model="infoForm.isBoard" placeholder="请选择">
                      <el-option label="是" :value="Number(0)"> </el-option>
                      <el-option label="否" :value="Number(1)"> </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="特长" prop="speciality">
                    <el-input
                      v-model="infoForm.speciality"
                      placeholder="请输入"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="户口性质" prop="residenceCode">
                    <el-select
                      v-model="infoForm.residenceCode"
                      placeholder="请选择"
                      clearable
                      filterable
                    >
                      <el-option
                        v-for="item in comData['户口']"
                        :key="item.code"
                        :label="item.name"
                        :value="item.code"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="户口所在地" prop="residenceLocation">
                    <el-cascader
                      style="width: 100%"
                      separator=""
                      filterable
                      :options="regionOptions"
                      v-model="infoForm.residenceLocation"
                    >
                    </el-cascader>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="户口地址" prop="residenceAddress">
                    <el-input
                      v-model="infoForm.residenceAddress"
                      placeholder="请输入"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="学生类别" prop="typeCode">
                    <el-select
                      placeholder="请选择学生类别"
                      v-model="infoForm.typeCode"
                      clearable
                      filterable
                    >
                      <el-option
                        v-for="item in comData['学生类别']"
                        :key="item.code"
                        :label="item.name"
                        :value="String(item.code)"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="当前状态" prop="currentStatusCode">
                    <el-select
                      placeholder="请选择当前状态"
                      v-model="infoForm.currentStatusCode"
                      clearable
                      filterable
                    >
                      <el-option
                        v-for="item in comData['学生当前状态']"
                        :key="item.code"
                        :label="item.name"
                        :value="String(item.code)"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="在校状态" prop="currentSchoolCode">
                    <el-select
                      placeholder="请选择在校状态"
                      v-model="infoForm.currentSchoolCode"
                      clearable
                      filterable
                    >
                      <el-option
                        v-for="item in comData['学生在校状态']"
                        :key="item.code"
                        :label="item.name"
                        :value="String(item.code)"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="就读方式" prop="attendType">
                    <el-select
                      placeholder="请选择就读方式"
                      v-model="infoForm.attendType"
                      clearable
                      filterable
                    >
                      <el-option
                        v-for="item in comData['就读方式']"
                        :key="item.code"
                        :label="item.name"
                        :value="String(item.code)"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-upload
                  :class="{ 'pic-card': Boolean(infoForm.imageUrl) }"
                  action="/gateway/api/basic/minio/upload"
                  list-type="picture-card"
                  :headers="headerObj"
                  :limit="1"
                  :file-list="infoForm.fileList"
                  :style="{
                    display: 'flex',
                    'flex-direction': 'column',
                    'align-items': 'center',
                  }"
                  :on-success="imageSuccess"
                  :before-upload="beforeAvatarUpload"
                  :on-remove="imageRemove"
                >
                  <i class="el-icon-plus" />
                  <div slot="tip">
                    <div
                      :style="{
                        'font-size': '16px',
                        'font-weight': 600,
                        margin: '10px 0 20px',
                        'text-align': 'center',
                      }"
                    >
                      学生照片
                    </div>
                    <div
                      :style="{
                        'text-align': 'center',
                      }"
                    >
                      （请上传照片，10M以内）
                    </div>
                  </div>
                </el-upload>
              </el-row>
            </el-form>
          </el-tab-pane>

          <el-tab-pane
            v-if="isAdd"
            label="学生荣誉"
            name="2"
            class="school-honors"
          >
            <section v-if="sepSchoolHonorInfoList" key="er-dfe0er">
              <el-card>
                <el-button type="primary" @click="addSchoolHonor"
                  >新增荣誉</el-button
                >
                <el-button type="primary" @click="openImportHonor"
                  >批量新增荣誉</el-button
                >
              </el-card>

              <el-card
                v-for="(item, index) in sepSchoolHonorInfoList"
                :key="index"
              >
                <el-form
                  :validate-on-rule-change="true"
                  :ref="'honorForm' + index"
                  :model="item"
                  :rules="honorRules"
                  label-width="120px"
                >
                  <el-row class="box">
                    <el-col :span="12">
                      <el-form-item
                        label="荣誉名称："
                        prop="name"
                        :rules="[
                          {
                            required: true,
                            message: '请输入',
                            trigger: ['blur', 'change'],
                          },
                        ]"
                      >
                        <el-input
                          size="small"
                          v-model="item.name"
                          class="content-input"
                          placeholder="请输入"
                        ></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12"> </el-col>
                  </el-row>
                  <el-row class="box">
                    <el-col :span="12">
                      <el-form-item
                        label="获奖时间："
                        prop="awardTime"
                        :rules="[
                          {
                            required: true,
                            message: '请选择',
                            trigger: ['blur', 'change'],
                          },
                        ]"
                      >
                        <el-date-picker
                          format="yyyy-MM-dd"
                          value-format="yyyy-MM-dd"
                          class="content-input"
                          v-model="item.awardTime"
                          type="date"
                          size="small"
                          placeholder="请选择"
                        ></el-date-picker>
                      </el-form-item>
                    </el-col>

                    <el-col :span="12">
                      <el-form-item label="获奖学年度：" prop="awardTermId">
                        <el-select
                          v-model="item.awardTermId"
                          size="small"
                          class="content-input"
                          clearable
                          filterable
                        >
                          <el-option
                            v-for="data in sepGradeInfoData"
                            :key="data.id + 'asd'"
                            :label="data.year + data.term"
                            :value="String(data.id)"
                          >
                          </el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row class="box">
                    <el-col :span="12">
                      <el-form-item
                        label="荣誉级别："
                        prop="level"
                        :rules="[
                          {
                            required: true,
                            message: '请选择',
                            trigger: ['blur', 'change'],
                          },
                        ]"
                      >
                        <el-select
                          v-model="item.level"
                          size="small"
                          class="content-input"
                          clearable
                          filterable
                        >
                          <el-option
                            v-for="data in comData['学生荣誉级别']"
                            :key="data.code"
                            :label="data.name"
                            :value="data.code"
                          >
                          </el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item
                        label="荣誉等级："
                        prop="awardLevel"
                        :rules="[
                          {
                            required: true,
                            message: '请选择',
                            trigger: ['blur', 'change'],
                          },
                        ]"
                      >
                        <el-select
                          v-model="item.awardLevel"
                          size="small"
                          class="content-input"
                          clearable
                          filterable
                        >
                          <el-option
                            v-for="data in comData['学生荣誉等级']"
                            :key="data.code"
                            :label="data.name"
                            :value="data.code"
                          >
                          </el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row class="box">
                    <el-col :span="12">
                      <el-form-item label="获奖类型：" prop="awardType">
                        <el-select
                          v-model="item.awardType"
                          size="small"
                          class="content-input"
                          clearable
                          filterable
                        >
                          <el-option
                            v-for="data in comData['学生获奖类型']"
                            :key="data.code"
                            :label="data.name"
                            :value="data.code"
                          >
                          </el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item
                        label="获奖类别："
                        prop="subjectType"
                        :rules="[
                          {
                            required: true,
                            message: '请选择',
                            trigger: ['blur', 'change'],
                          },
                        ]"
                      >
                        <el-select
                          v-model="item.subjectType"
                          size="small"
                          class="content-input"
                          clearable
                          filterable
                        >
                          <el-option
                            v-for="data in comData['学生获奖类别']"
                            :key="data.code"
                            :label="data.name"
                            :value="data.code"
                          >
                          </el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                  </el-row>

                  <el-row class="box">
                    <el-col :span="12">
                      <el-form-item label="颁奖单位：" prop="rewardsBureau">
                        <el-input
                          v-model="item.rewardsBureau"
                          size="small"
                          class="content-input"
                          placeholder="请输入"
                        >
                        </el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>

                  <el-row class="box">
                    <el-form-item label="荣誉照片：">
                      <section class="avatar-box">
                        <el-upload
                          action="/gateway/api/basic/minio/upload"
                          :headers="headerObj"
                          class="avatar"
                          :before-upload="beforeAvatarUpload"
                          :on-remove="
                            (file, fileList) => {
                              HonorImageRemove(index, file, fileList);
                            }
                          "
                          :on-success="
                            (res, file, fileList) => {
                              HonorImageSuccess(index, res, file, fileList);
                            }
                          "
                          :file-list="item.HonorFileList"
                          list-type="picture-card"
                        >
                          <i class="el-icon-plus"></i>
                        </el-upload>
                      </section>
                    </el-form-item>
                  </el-row>
                  <el-form-item>
                    <el-row class="box">
                      <i
                        class="el-icon-delete"
                        style="font-size: 20px; float: right"
                        @click="delHonor(item, index)"
                      ></i>
                    </el-row>
                  </el-form-item>
                </el-form>
              </el-card>
            </section>
            <!-- <div v-else>暂无数据</div> -->
          </el-tab-pane>
        </el-tabs>
        <div
          v-if="
            addStudentForm.title !== '新增学生信息'
          "
          class="switch-btn cursor iconfont"
          :class="[isShow ? 'icon-yanjing' : 'icon-biyan']"
          @click="handleClickIsShow"
        ></div>
      </div>
      <div class="foot">
        <el-button type="primary" @click.native.prevent="close()"
          >取消</el-button
        >
        <el-button type="primary" @click.native.prevent="sub()">
          {{ activeName === "1" ? "保存基本信息" : "保存学生荣誉" }}
        </el-button>
      </div>
    </el-dialog>
  </section>
</template>
<script>
import { Message } from 'element-ui'
import { encrypt } from '@/utils/crypto'
import {
  add,
  update,
  districtList,
  sepGradeInfo,
  addHonor,
  editHonor,
  deleteHonor,
  queryNativePlace,
  validRepeatAccount,
  downloadHonorTemplate
} from '@/views/children/basic/js/studentInfo'
import { getIdCardInfo } from '@/api/user'
export default {
  name: 'addSchoolInfo',
  inject: ['handleSearch'],

  props: {
    addStudentForm: {
      type: Object
    },
    data: {
      type: Object
    },
    comData: {
      type: Object
    },
    isAdd: {
      type: Boolean
    },
    editDataInfo: {},
    editRowID: {}
  },

  mounted () {
    this.getDistrictList()
    this.sepGradeInfoList({})
    this.getRegionData()
    // 荣誉级别
    // getHonor().then(res => {
    //   this.honorLevels = res.data
    // })
  },

  data () {
    return {
      isShow: true,
      honorImportParam: {},
      isImportHonor: false,
      oldAccount: '',
      innerVisible: false,
      innerDialogText: '',
      sepGradeInfoData: [],

      honorLevels: [],
      setDisabled: {
        disabledDate (time) {
          return time.getTime() > Date.now()
        }
      },

      headerObj: {
        token: JSON.parse(localStorage.getItem('Standard__Access-Token')).value
      },
      districtData: [],
      activeName: '1',
      // 基础表单校验规则
      rules: {
        typeName: [{ required: true, validator: this.validateTypeName }],
        name: [
          {
            required: true,
            message: '请输入内容',
            trigger: ['blur', 'change']
          },
          {
            min: 1,
            max: 30,
            message: '长度在 1 到 30 个字符',
            trigger: ['blur', 'change']
          }
        ],
        contact: [
          {
            required: true,
            validator: this.validatorPhone,
            trigger: ['blur', 'change']
          }
        ],
        code: [
          {
            required: true,
            message: '请输入内容',
            trigger: ['blur', 'change']
          }
        ],
        address: [
          {
            required: true,
            message: '请输入内容',
            trigger: ['blur', 'change']
          }
        ],
        nationality: [
          {
            required: true,
            message: '请输入内容',
            trigger: ['blur', 'change']
          }
        ],
        cardType: [
          {
            required: true,
            message: '请输入内容',
            trigger: ['blur', 'change']
          }
        ],
        idCard: [{ required: true, validator: this.validatorId }]
        // birthday: [
        //   {
        //     required: true,
        //     message: '请输入内容',
        //     trigger: ['blur', 'change']
        //   }
        // ],
        // nativePlace: [
        //   {
        //     required: true,
        //     validator: this.validatorNativePlace
        //     // message: '请输入内容',
        //     // trigger: ['blur', 'change']
        //   }
        // ],
        // gender: [
        //   {
        //     required: true,
        //     message: '请输入内容',
        //     trigger: ['blur', 'change']
        //   }
        // ]
      },

      honorRules: {
        name: [
          {
            required: true,
            message: '请输入内容',
            trigger: ['blur', 'change']
          }
        ],
        level: [
          {
            required: true,
            message: '请输入内容',
            trigger: ['blur', 'change']
          }
        ],
        rewardsBureau: [
          {
            required: true,
            message: '请输入内容',
            trigger: ['blur', 'change']
          }
        ]
      },
      content: '',

      uploadVisible: false,
      options: [],
      // 表单信息默认数据
      sepSchoolHonorInfoList: [],
      infoForm: {
        fileList: [],
        imageUrl: '',
        name: '',
        code: '',
        pinyinName: '',
        englishName: '',
        contact: '',
        address: '',
        status: '',
        isCreateAccount: 1,
        account: '',
        schoolDistrictNo: '',
        gender: '',
        nationality: '',
        cardType: '1',
        idCard: '',
        birthday: '',
        birthPlace: [],
        nativePlace: [],
        residenceAddress: '',
        nation: '',
        politicsStatus: '',
        compatriotCode: '',
        religionCode: '',
        healthCode: '',
        bloodTypeCode: '',
        isOnlyChild: '',
        isMigrantChild: '',
        isOrphan: '',
        isMartyrChild: '',
        isDisabled: '',
        disabledCode: '',
        isBoard: '',
        speciality: '',
        residenceCode: '',
        residenceLocation: [],
        typeCode: '',
        currentStatusCode: '',
        currentSchoolCode: '',
        attendType: ''
      },
      regionOptions: []
    }
  },
  watch: {
    data: {
      deep: true,
      immediate: true,
      handler (newVal, oldVal) {
        this.infoForm = {
          ...newVal,
          disabledCode: newVal.disabledCode ? Number(newVal.disabledCode) : ''
        }
        if (
          this.infoForm.fileList &&
          this.infoForm.fileList[0] &&
          this.infoForm.fileList[0].url
        ) {
          this.infoForm.fileList[0].url = `/gateway/api/basic/minio/getFileSource?fileName=${this.infoForm.imageUrl}`
        }

        if (this.sepSchoolHonorInfoList) {
          this.sepSchoolHonorInfoList = [...newVal.sepSchoolHonorInfoList].map(
            (item) => {
              return {
                ...item,
                HonorFileList: item.HonorFileList
                  ? item.HonorFileList.map((item1) => {
                    return {
                      ...item1,
                      url: `/gateway/api/basic/minio/getFileSource?fileName=${item1.url}`
                    }
                  })
                  : []
              }
            }
          )
        }
      }
    },
    studentName () {
      if (
        this.addStudentForm.title === '新增学生信息' &&
        this.infoForm &&
        this.infoForm.isCreateAccount
      ) {
        this.$set(this.infoForm, 'account', this.studentName)
      }
    },
    isDisableAccount () {
      if (
        this.isDisableAccount &&
        this.addStudentForm.title === '新增学生信息'
      ) {
        this.$set(this.infoForm, 'account', '')
      }
    }
  },

  computed: {
    isDisableAccount () {
      return (
        (this.infoForm && !this.infoForm.isCreateAccount) ||
        this.addStudentForm.title === '编辑学生信息'
      )
    },
    studentName () {
      return this.infoForm && this.infoForm.name
    }
  },

  methods: {
    handleClickIsShow () {
      this.isShow = !this.isShow
      this.$refs.AccDesensitization.doShow()
      this.$refs.cellularPhone.doShow()
    },
    blurSearchIdInfo () {
      if (this.infoForm.cardType !== '1' || this.infoForm.idCard === '') return
      getIdCardInfo({ encryptParam: encrypt(this.infoForm.idCard) }).then(
        (res) => {
          const { data } = res
          if (data.age === -1) return this.$message.warning(data.birthDay)
          this.$set(this.infoForm, 'nativePlace', data.nativePlace.split(','))
          this.$set(this.infoForm, 'birthPlace', data.nativePlace.split(','))
          this.$set(this.infoForm, 'birthday', data.birthDay)
          this.$set(this.infoForm, 'gender', data.gender)
        }
      )
    },
    handleChangeCardType () {
      this.infoForm.idCard.length === 18 && this.blurSearchIdInfo()
      // this.infoForm.nativePlace = ''
      // this.infoForm.birthPlace = ''
      // this.infoForm.birthday = ''
      // this.infoForm.gender = null
    },
    honorTemplate () {
      downloadHonorTemplate()
    },
    handlefileSuccess (response) {
      if (response.code === 0) {
        this.$message.success('导入成功！')
        this.editDataInfo(this.editRowID)
        setTimeout(() => {
          this.isImportHonor = false
        }, 0)
      } else {
        this.$message.error(response.msg)
      }
    },
    beforeUpload (file) {
      // this.honorImportParam = { studentCode: this.infoForm.code };
      const extension = file.name.split('.')[1] === 'xls'
      const extension2 = file.name.split('.')[1] === 'xlsx'
      const zipType = file.name.split('.')[1] === 'zip'
      const isLt2M = file.size / 1024 / 1024 < 200
      if (!extension && !extension2 && !zipType) {
        this.$message.warning('导入模板只能是xls、xlsx、zip格式!')
        return false
      } else if (!isLt2M) {
        this.$message.warning('导入模板大小不能超过 200MB!')
        return false
      } else {
        return true
      }
    },

    openImportHonor () {
      this.isImportHonor = true
    },

    closeImportHonor () {
      this.isImportHonor = false
    },

    resetName () {
      this.infoForm.account = this.innerDialogText
      setTimeout(() => {
        this.sub()
      }, 0)
    },

    closeInnerDialog () {
      this.innerVisible = false
    },

    openFormDialog () {
      this.activeName = '1'
      if (this.$refs.basicForm) {
        this.$refs.basicForm.clearValidate()
      }
    },

    checkForm (formName) {
      return new Promise((resolve, reject) => {
        this.$refs[formName][0].validate((valid) => {
          if (valid) {
            resolve()
          } else {
            Message({
              message: '校验未通过！',
              type: 'error',
              offset: 100,
              customClass: 'm-index'
            })
            reject(new Error('校验失败'))
          }
        })
      })
    },
    async getRegionData () {
      const regionData = require('@/assets/region/region.json')
      try {
        const res = await queryNativePlace({
          type: 'ALL'
        })
        if (res.code === 0) {
          this.regionOptions = this.setRegionData(res.data)
        }
      } catch (e) {
        this.regionOptions = this.setRegionData(regionData)
      }
    },
    setRegionData (region) {
      // 处理省市区接口返回数据添加指定字段
      if (Array.isArray(region) && region.length) {
        region.map((n) => {
          n.label = n.name
          n.value = n.adcode
          if (n.children && n.children.length) {
            this.setRegionData(n.children)
          }
        })
      }
      return region
    },
    setRegion (region) {
      return region && region.length ? region.join(',') : ''
    },

    // 删除当前添加的照片
    HonorImageRemove (index, file, fileList) {
      let temp1 = this.sepSchoolHonorInfoList[index].HonorFileList.filter(
        (item) => {
          return item.uid !== file.uid
        }
      )

      this.sepSchoolHonorInfoList[index].HonorFileList = temp1
    },

    HonorImageSuccess (index, res, file, fileList) {
      this.sepSchoolHonorInfoList[index].HonorFileList = fileList

      if (res.code === 0) {
        Message({
          message: '上传图片成功',
          type: 'success',
          offset: 100,
          customClass: 'm-index'
        })
      } else {
        let temp = this.sepSchoolHonorInfoList[index].HonorFileList.filter(
          (item) => {
            return item.uid !== file.uid
          }
        )

        this.sepSchoolHonorInfoList[index].HonorFileList = temp
        Message({
          message: res.msg,
          type: 'error',
          offset: 100,
          customClass: 'm-index'
        })
      }
    },

    // 新增学生荣誉
    addSchoolHonor () {
      this.sepSchoolHonorInfoList.unshift({
        awardLevel: '',
        awardPic: '',
        awardTermId: '',
        awardTime: '',
        awardType: '',
        level: '',
        name: '',
        rewardsBureau: '',
        subjectType: '',
        HonorFileList: []
      })
    },

    // 删除当前条学生荣誉
    delHonor (data, index) {
      this.$confirm('此操作将删除该生该条荣誉信息 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (data.id || data.id === 0) {
          deleteHonor(data.id).then(({ code, msg }) => {
            if (code === 0) {
              this.$message.success('删除成功')
            } else {
              this.$message.warning(msg)
            }
          })
        }

        this.sepSchoolHonorInfoList.splice(index, 1)
      })
    },

    isDisabledChange (value) {
      if (value === 1) {
        this.infoForm.disabledCode = ''
      }
    },

    beforeAvatarUpload (file) {
      const isJPG =
        file.type === 'image/jpeg' ||
        file.type === 'image/bmp' ||
        file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 10

      if (!isJPG) {
        Message({
          message: '上传图片只能是 JPG、PNG 、BMP 格式!',
          type: 'error',
          offset: 100,
          customClass: 'm-index'
        })
      }
      if (!isLt2M) {
        Message({
          message: '上传图片大小不能超过 10MB!',
          type: 'error',
          offset: 100,
          customClass: 'm-index'
        })
      }
      return isJPG && isLt2M
    },

    imageSuccess (res, file, fileList) {
      if (res.code === 0) {
        this.$set(this.infoForm, 'imageUrl', res.data)
        this.$set(this.infoForm, 'fileList', fileList)
        Message({
          message: '上传图片成功',
          type: 'success',
          offset: 100,
          customClass: 'm-index'
        })
      } else {
        this.$set(this.infoForm, 'imageUrl', '')
        this.$set(this.infoForm, 'fileList', [])
        Message({
          message: res.msg,
          type: 'error',
          offset: 100,
          customClass: 'm-index'
        })
      }
    },

    imageRemove (file) {
      this.$set(this.infoForm, 'imageUrl', '')
      this.$set(this.infoForm, 'fileList', [])
    },

    async getDistrictList (params) {
      const { code, msg, data } = await districtList(params)
      if (code === 0) {
        this.districtData = data
      } else {
        this.$message.warning(msg)
      }
    },
    async sepGradeInfoList (params) {
      const { code, msg, data } = await sepGradeInfo(params)
      if (code === 0) {
        this.sepGradeInfoData = data.records
      } else {
        this.$message.warning(msg)
      }
    },

    // 身份证号
    validatorId (rule, value, callback) {
      if (value === undefined || value === '') {
        callback(new Error('证件号号不能为空'))
      } else {
        callback()
      }
      // else if (!/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(value)) {
      //   callback(new Error('身份证号格式错误'))
      // }
    },
    // 籍贯校验 修复 因导入而存在只有一级信息的数据 编辑是因为有数据 不会触发必填校验 但因为数据不足 无法回填
    validatorNativePlace (rule, value, callback) {
      if (value === undefined || value === '') {
        callback(new Error('请选择籍贯'))
      }
      // 判断是否有子节点
      let data = this.$refs.nativePlace.getCheckedNodes()
      if (data.length === 0 || data[0].hasChildren) {
        callback(new Error('请选择籍贯'))
      } else {
        callback()
      }
    },
    // 校验手机号
    validatorPhone (rule, value, callback) {
      if (value === undefined || value === '') {
        callback(new Error('手机号不能为空'))
      } else if (!/^1\d{10}$/.test(value)) {
        callback(new Error('手机号格式错误'))
      } else {
        callback()
      }
    },

    close () {
      this.$refs['basicForm'].resetFields()
      this.$emit('closeaddStudentForm', false)
      this.activeName = '1'
      this.handleSearch()
    },

    async sub () {
      let _this = this
      async function send (data, ajax) {
        let params = data.map((item) => {
          let data = {
            awardLevel: item.awardLevel,

            awardTime: item.awardTime.split(' ')[0],
            awardType: item.awardType,
            id: item.id,
            level: item.level,
            name: item.name,
            rewardsBureau: item.rewardsBureau,
            subjectType: item.subjectType,
            studentCode: _this.infoForm.code,
            schoolNo: _this.infoForm.schoolNo,
            studentNo: _this.infoForm.studentNo,
            awardPic: item.HonorFileList.filter(
              (item) => item.response.code === 0
            )
              .map((item) => item.response.data)
              .join(',')
          }

          if (item.awardTermId && item.awardTermId !== '') {
            data.awardTermId = Number(item.awardTermId)
          } else {
            data.awardTermId = ''
          }

          if (item.id || item.id === 0) {
            data.id = item.id
          }
          return data
        })
        const { code, msg } = await ajax(params)
        if (code === 0) {
          _this.close()
          _this.$message.success('保存成功！')
        } else {
          Message({
            message: msg,
            type: 'error',
            offset: 150,
            customClass: 'm-index'
          })
        }
      }

      let {
        imageUrl,
        name,
        code,
        pinyinName,
        englishName,
        contact,
        address,
        status,
        isCreateAccount,
        account,
        schoolDistrictNo,
        gender,
        nationality,
        cardType,
        idCard,
        birthday,
        birthPlace,
        nativePlace,
        nation,
        politicsStatus,
        compatriotCode,
        religionCode,
        healthCode,
        bloodTypeCode,
        isOnlyChild,
        isMigrantChild,
        isOrphan,
        isMartyrChild,
        isDisabled,
        disabledCode,
        isBoard,
        speciality,
        residenceCode,
        residenceLocation,
        typeCode,
        currentStatusCode,
        currentSchoolCode,
        attendType,
        residenceAddress
      } = this.infoForm
      let data = {
        imageUrl,
        name,
        code,
        pinyinName,
        englishName,
        contact,
        address,
        status,
        isCreateAccount,
        account,
        schoolDistrictNo,
        gender,
        nationality,
        cardType,
        idCard,
        birthday,
        birthPlace: this.setRegion(birthPlace),
        nativePlace: this.setRegion(nativePlace),
        nation,
        politicsStatus,
        compatriotCode,
        religionCode,
        healthCode,
        bloodTypeCode,
        isOnlyChild,
        isMigrantChild,
        isOrphan,
        isMartyrChild,
        isDisabled,
        disabledCode,
        isBoard,
        speciality,
        residenceCode,
        residenceLocation: this.setRegion(residenceLocation),
        typeCode,
        currentStatusCode,
        currentSchoolCode,
        attendType,
        residenceAddress
      }

      if (this.addStudentForm.title === '新增学生信息') {
        this.$refs['basicForm'].validate(async (valid) => {
          if (valid) {
            // 新增学生基本信息
            if (this.infoForm.account) {
              let res = await validRepeatAccount({
                account: this.infoForm.account,
                code: '',
                downloadType: 0,
                name: '',
                nation: '',
                pageNum: 1,
                pageSize: 10,
                status: ''
              })
              if (res.code === 0) {
                if (res.data.isExist === '0') {
                  add({ encryptParam: encrypt(data) })
                    .then((res) => {
                      if (res.code === 0) {
                        this.close()

                        this.$message.success('新增成功')
                        this.closeInnerDialog()
                      } else {
                        Message({
                          message: res.msg,
                          type: 'warning',
                          offset: 100,
                          customClass: 'm-index'
                        })
                        this.closeInnerDialog()
                      }
                    })
                    .catch(() => {
                      this.closeInnerDialog()
                    })
                } else {
                  this.innerVisible = true
                  this.oldAccount = this.infoForm.account
                  this.innerDialogText = res.data.newAccount
                }
              } else {
                Message({
                  message: res.msg,
                  type: 'warning',
                  offset: 100,
                  customClass: 'm-index'
                })
              }
            } else {
              add({ encryptParam: encrypt(data) })
                .then((res) => {
                  if (res.code === 0) {
                    this.close()

                    this.$message.success('新增成功')
                    this.closeInnerDialog()
                  } else {
                    Message({
                      message: res.msg,
                      type: 'warning',
                      offset: 100,
                      customClass: 'm-index'
                    })
                    this.closeInnerDialog()
                  }
                })
                .catch(() => {
                  this.closeInnerDialog()
                })
            }
          }
        })
      } else if (this.addStudentForm.title === '编辑学生信息') {
        if (this.activeName === '2') {
          // 荣誉操作

          let honorInfo = this.sepSchoolHonorInfoList

          Promise.all(
            honorInfo.map((item, index) => {
              return this.checkForm('honorForm' + index)
            })
          ).then(() => {
            // 编辑
            let editData = honorInfo.filter((item) => {
              return item.id !== undefined
            })

            editData.length > 0 && send(editData, editHonor)
            // 新增

            let addData = honorInfo.filter((item) => {
              return item.id === undefined
            })
            addData.length > 0 && send(addData, addHonor)
            // 未操作
            if (editData.length <= 0 && addData.length <= 0) {
              Message({
                message: '您未新增学生荣誉，请新增后保存!',
                type: 'warning',
                offset: 100,
                customClass: 'm-index'
              })
            }
          })
        } else {
          this.$refs['basicForm'].validate((valid) => {
            if (valid) {
              update({
                encryptParam: encrypt({ ...data, id: this.infoForm.id })
              }).then((res) => {
                if (res.code === 0) {
                  this.close()

                  this.$message.success('修改成功')
                }
              })
            }
          })
        }
      }
    },

    validateTypeName (rule, value, callback) {
      if (value === undefined || value.toString().trim() === '') {
        callback(new Error('请输入类型名称'))
      } else if (value.length > 30) {
        callback(new Error('类型名称不能超过30个字符'))
      } else {
        callback()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.switch-btn {
  width: 50px;
  height: 30px;
  line-height: 30px;
  text-align: center;
  font-size: 20px;
  position: absolute;
  right: 0;
  top: 5px;
}
.m-index {
  z-index: 3000 !important;
}

.import-honor-des {
  .title {
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 30px;
  }

  .box1 {
    margin-bottom: 20px;

    .btn {
      margin-left: 20px;
      padding: 0;
    }
  }

  .text {
    margin-bottom: 20px;
  }
}

.app-inner {
  /deep/ .foot {
    text-align: center;

    > * {
      margin: 20px 80px;
    }
  }

  .info-school-tab {
    .el-select,
    .el-select--small {
      width: 100%;
    }
  }

  // 校史发展 教学理念 校园特色场景
  .school-history-development,
  .teaching-concept,
  .campus-characteristic-scene {
    .box {
      display: flex;
      margin: 20px;

      .title {
        flex: 0.1;
      }

      .content {
        flex: 1;
      }

      .editor-content {
        height: 300px;
        border: 1px solid #c9d8db;
        border-top: none;
        min-height: 300px;
      }
    }
  }

  // 学生荣誉
  .school-honors {
    .box {
      // margin: 20px;
      .title {
        float: left;
        width: 120px;
      }

      .content-input {
        float: left;
        width: 300px;
      }

      .avatar-box :first-child {
        margin-left: 0;
      }

      .avatar {
        float: left;
        margin-left: 10px;
      }
    }
  }

  ::v-deep {
    .pic-card {
      .el-upload--picture-card {
        display: none;
      }
    }
  }
}
</style>
